package com.wujilee.wujileenetty.demos.web.nio;

/**
 * 异步io (只能用来读文件 不能用在网络IO的读取上)
 */

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousFileChannel;
import java.nio.channels.CompletionHandler;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

/**
 * @author liwuji
 * @date 2024/8/6
 * @desc 异步io  异步io有一个问题 如果byterBuffer没有一次读取完 要主动去调用获取接下来的数据
 **/
@Slf4j
public class SnyFile {
    public static void main(String[] args) throws IOException, InterruptedException {
        log.info("开始读取");
        AsynchronousFileChannel channel = AsynchronousFileChannel.open(Paths.get("/Users/liwuji/demo.txt"), StandardOpenOption.READ);
        ByteBuffer allocate = ByteBuffer.allocate(1024);
        channel.read(allocate, 0, allocate, new CompletionHandler<Integer, ByteBuffer>() {
            @Override
            public void completed(Integer result, ByteBuffer attachment) {
                log.info("读取完成");
                attachment.flip();
                byte[]  buffer = new byte[result];
                attachment.get(buffer);

                System.out.println(new String(buffer));
                attachment.clear();
            }
            @Override
            public void failed(Throwable exc, ByteBuffer attachment) {
                log.info("读取异常");
            }
        });


        while (true) {
            Thread.sleep(100L);
        }

    }
}
